package tz.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import tz.preprocessing.bagOfWords.BagOfWords;

public class WekaFile
{
	
		
	String relation;
	ArrayList<WekaAttribute> lstAttributes;
		
	public WekaFile()
	{
		lstAttributes = new ArrayList<WekaAttribute>();
	}
	
	public String getRelation()
	{
		return relation;
	}

	public void setRelation(String relation)
	{
		this.relation = relation;
	}

	public void addAttribute(WekaAttribute attr)
	{
		lstAttributes.add(attr);
	}


	
	public void write2wekaFileFormat(File file, Map<Article, BagOfWords> mapData) throws Exception 
	{
		FileWriter fw = new FileWriter(file);
		writeRelation(fw, getRelation());
		//WekaAttribute[] sortAtribut = (WekaAttribute[])lstAttributes.toArray();
		//Arrays.sort(sortAtribut); //Sortiramo atribute za hitrejše iskanje po atributih.
		writeAttribute(fw, new WekaAttribute("ID-number","real"));
		for(WekaAttribute wa : lstAttributes)
		{
			writeAttribute(fw, wa);
		}
		writeLine(fw, "@data");
		for(Article a : mapData.keySet())
		{
			BagOfWords bag = mapData.get(a);
			fw.write(a.getArticleID()+"");
			for(WekaAttribute w : lstAttributes)
			{

				Double v = bag.getBag().get(w.name);
				if(v == null)
				{
					fw.write(",0");
				}
				else 
				{
					fw.write(","+v);
				}
			}
			fw.write("\n");
		}
		fw.close();
	}
	
	private static void writeRelation(FileWriter fw, String relationName) throws Exception
	{
		writeLine(fw, "@relation '"+relationName+"'");
	}
	
	private static void writeAttribute(FileWriter fw, WekaAttribute attr) throws Exception
	{
		writeLine(fw, attr.toString());
	}
	
	
	private static void writeDataLine(FileWriter fw, List<String> lstData) throws IOException
	{
		String str;
		for(int i = 0; i < lstData.size(); i++)
		{
			str = lstData.get(i);
			if(i < lstData.size()-1)
			{
				fw.write(str+",");
			}
			else
			{
				fw.write(str);
			}
		}
		fw.write("\n");
	}
	
	private static void writeLine(FileWriter fw, String line) throws Exception
	{
		fw.write(line + "\n");
	}
}
